//
//  Timer.swift
//  If Light
//
//  Created by 姬向阳 on 2020/5/7.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI

class Timer {
    // 单例
    static var shared = Timer()
    private init() {}
    
    // 在global线程里创建一个时间源
    private var timer : DispatchSourceTimer!
    private var durations = 0
    
    /// 启动计时器
    func startTimer(completion: @escaping (String) -> Void ) {
        // 在global线程里创建一个时间源
        timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        // 计时器归零
        durations = 0
        // 设定起始时间.now() 设置循环时间100微秒
        timer.schedule(deadline: .now(), repeating: .microseconds(100))
        // 设定触发时间
        timer.setEventHandler {
            // 返回主线程处理,保证线程安全
            DispatchQueue.main.async {
                let timeString = self.timeMethod()
                completion(timeString)
            }
        }
        // 检查是否取消,取消状态下resume会导致崩溃
        if timer.isCancelled {
            return
        }
        // 启动,重复启动也会导致崩溃
        timer.resume()
    }
    
    /// 取消计时器
    func cancelTimer() {
        timer.cancel()
        timer = nil
    }
    
    /// 处理时间字符串,分/秒/毫秒转换,实现秒针后两位计时
    private func timeMethod() -> String{
        durations += 1

        let min = durations >= 600000 ? durations/600000 : 0
        let seconds = (durations - min * 600000) / 10000
        let microseconds = durations - min * 600000 - seconds * 10000
        
        let minString = min >= 10 ? "\(min)" : "0\(min)"
        let secondsString = seconds >= 10 ? "\(seconds)" : "0\(seconds)"
        let microsecondsString = microseconds/100 >= 10 ? "\(microseconds/100)" : "0\(microseconds/100)"
        
        let timeString = minString + ":" + secondsString + ":" + microsecondsString
        
        return timeString
    }
}
